import { initGlobalState, MicroAppStateActions } from "qiankun";

type MyMicroAppStateActions = MicroAppStateActions & {
  getGlobalState: (key?: string) => any;
};

const initialState = {
  qqMusic: {
    bandWidth: 100,
    startFrequency: 90,
    stopFrequency: 100,
  },
  neteaseMusic: {
    bandWidth: 100,
    startFrequency: 90,
    stopFrequency: 100,
  },
};
const actions: MyMicroAppStateActions = initGlobalState(initialState);

actions.onGlobalStateChange((newState, prev) => {
  // state: 变更后的状态; prev 变更前的状态
  console.log("main change", JSON.stringify(newState), JSON.stringify(prev));

  for (let key in newState) {
    initialState[key] = newState[key];
  }
});

actions.getGlobalState = (key) => {
  // 有key，表示取globalState下的某个子级对象
  // 无key，表示取全部
  return key ? initialState[key] : initialState;
};

export default actions;
